package com.yanqu.road.server.cmd.mall;

import com.yanqu.road.entity.config.goods.MallInfo;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.enums.eShopType;
import com.yanqu.road.entity.player.ReturnData;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.mall.MallProto;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.mall.MallModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.manger.config.MallMgr;
import com.yanqu.road.server.manger.maidian.entity.BuyShopItem;
import com.yanqu.road.server.manger.maidian.resource.BuyItemLog;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

@Cmd(code = Protocol.S_MALL_BUY_GOODS, desc = "购买物品")
public class BuyGoodsCmd extends AbstractCommand {

	private int mallId;

	private int count;

	private String reward;

	@Override
	public boolean parseData(YanQuMessage packet) throws Exception {
		MallProto.BuyGoodsReqMsg reqMsg = MallProto.BuyGoodsReqMsg.parseFrom(packet.getBytes());
		mallId = reqMsg.getMallId();
		count = reqMsg.getCount();
		return true;
	}

	@Override
	public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
		ReturnData returnData = player.getModule(MallModule.class).preBuyGoods(mallId, count);
		ret = returnData.getRet();
		if (ret == 0) {
			Property consume = PropertyHelper.parseStringToProperty(returnData.getParams().get(0));
			if (player.getModule(CurrencyModule.class).removeCurrency(consume, eLogMoneyType.Mall, eLogMoneyType.MallBuy, mallId + ":" + count)) {
				reward = player.getModule(MallModule.class).buyGoods(mallId, count);

				MallInfo mallInfo = MallMgr.getMallInfoByMallId(mallId);
				if(mallInfo != null){
					//财神商店兑换
					if(eShopType.MammonMall.getValue() == mallInfo.getShopType()){
						player.notifyListener(eGamePlayerEventType.MammonShopWakeupProcess.getValue(), mallInfo);
					}
				}
				BuyItemLog.trackShopBuyItemSingle(player, new BuyShopItem(mallInfo, count, consume, PropertyHelper.parseStringToProperty(reward))) ;
			} else {
				ret = GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
			}
		}
	}

	@Override
	public void sendData(GamePlayer player) {
		MallProto.BuyGoodsRespMsg.Builder respMsg = MallProto.BuyGoodsRespMsg.newBuilder();
		respMsg.setRet(ret);
		if(!StringUtils.isNullOrEmpty(reward)){
			respMsg.setReward(reward);
		}
		player.sendPacket(Protocol.U_MALL_BUY_GOODS, respMsg);
	}
}
